<template>
  <div class="service-hours">
    <!-- 时长统计卡片 -->
    <el-card class="summary-card" v-loading="loading.stats">
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="summary-item total">
            <div class="item-icon">
              <el-icon><Timer /></el-icon>
            </div>
            <div class="item-info">
              <div class="item-value">{{ summary.totalHours || 0 }}</div>
              <div class="item-label">总服务时长（小时）</div>
            </div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="summary-item month">
            <div class="item-icon">
              <el-icon><Calendar /></el-icon>
            </div>
            <div class="item-info">
              <div class="item-value">{{ summary.monthHours || 0 }}</div>
              <div class="item-label">本月服务时长（小时）</div>
            </div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="summary-item rank">
            <div class="item-icon">
              <el-icon><Trophy /></el-icon>
            </div>
            <div class="item-info">
              <div class="item-value">{{ summary.rank || '暂无排名' }}</div>
              <div class="item-label">时长排名</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 时长趋势图 -->
    <el-card class="chart-card" v-loading="loading.chart">
      <template #header>
        <div class="card-header">
          <h3>服务时长趋势</h3>
          <el-radio-group v-model="timeRange" size="small" @change="handleTimeRangeChange">
            <el-radio-button label="week">周</el-radio-button>
            <el-radio-button label="month">月</el-radio-button>
            <el-radio-button label="year">年</el-radio-button>
          </el-radio-group>
        </div>
      </template>
      <div class="chart-container">
        <v-chart class="chart" :option="chartOption" autoresize />
      </div>
    </el-card>

    <!-- 时长记录表格 -->
    <el-card class="records-card" v-loading="loading.records">
      <template #header>
        <div class="card-header">
          <h3>服务记录</h3>
          <div class="header-actions">
            <el-button type="primary" plain @click="exportRecords">
              导出记录
            </el-button>
          </div>
        </div>
      </template>

      <el-table :data="records" style="width: 100%">
        <el-table-column prop="date" label="日期" width="120" />
        <el-table-column prop="project" label="项目名称" min-width="200" />
        <el-table-column prop="organization" label="主办方" width="150" />
        <el-table-column prop="type" label="服务类型" width="120">
          <template #default="scope">
            <el-tag :type="getTagType(scope.row.type)">
              {{ scope.row.type }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="hours" label="时长(小时)" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'verified' ? 'success' : 'warning'">
              {{ scope.row.status === 'verified' ? '已认证' : '待认证' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          @current-change="handlePageChange"
          background
          layout="prev, pager, next"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { Timer, Calendar, Trophy } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart } from 'echarts/charts'
import {
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import { getServiceHours, getServiceHoursTrend } from '@/api/volunteer-dashboard'

use([
  CanvasRenderer,
  LineChart,
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent
])

const timeRange = ref('month')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 加载状态
const loading = ref({
  stats: false,
  chart: false,
  records: false
})

// 服务时长统计数据
const summary = ref({
  totalHours: 0,
  monthHours: 0,
  rank: ''
})

// 服务时长记录
const records = ref([])

// 图表配置
const chartOption = ref({
  tooltip: {
    trigger: 'axis'
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: []
  },
  yAxis: {
    type: 'value',
    name: '小时'
  },
  series: [
    {
      name: '服务时长',
      type: 'line',
      smooth: true,
      data: [],
      itemStyle: {
        color: '#409EFF'
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            {
              offset: 0,
              color: 'rgba(64,158,255,0.2)'
            },
            {
              offset: 1,
              color: 'rgba(64,158,255,0)'
            }
          ]
        }
      }
    }
  ]
})

// 获取服务时长记录
const fetchServiceHours = async () => {
  loading.value.records = true
  loading.value.stats = true
  try {
    const res = await getServiceHours({
      page: currentPage.value,
      pageSize: pageSize.value
    })
    records.value = res.data.items
    total.value = res.data.total
    
    // 设置统计数据
    summary.value = res.data.summary
  } catch (error) {
    console.error('获取服务时长记录失败', error)
    ElMessage.error('获取服务时长记录失败')
  } finally {
    loading.value.records = false
    loading.value.stats = false
  }
}

// 获取服务时长趋势
const fetchServiceHoursTrend = async () => {
  loading.value.chart = true
  try {
    const res = await getServiceHoursTrend({ timeRange: timeRange.value })
    chartOption.value.xAxis.data = res.data.dates
    chartOption.value.series[0].data = res.data.hours
  } catch (error) {
    console.error('获取服务时长趋势失败', error)
    ElMessage.error('获取服务时长趋势失败')
  } finally {
    loading.value.chart = false
  }
}

// 监听分页变化
const handlePageChange = () => {
  fetchServiceHours()
}

// 监听时间范围变化重新获取数据
const handleTimeRangeChange = () => {
  fetchServiceHoursTrend()
}

// 处理导出记录
const exportRecords = () => {
  // TODO: 实现导出功能
  ElMessage.success('记录导出成功')
}

// 获取标签类型
const getTagType = (type) => {
  const types = {
    '环境保护': 'success',
    '科研调查': 'primary',
    '科普宣传': 'warning',
    '社区服务': 'info',
    '其他': 'danger'
  }
  return types[type] || 'info'
}

// 页面加载时获取数据
onMounted(() => {
  fetchServiceHours()
  fetchServiceHoursTrend()
})
</script>

<style scoped lang="scss">
.service-hours {
  .summary-card {
    margin-bottom: 20px;

    .summary-item {
      display: flex;
      align-items: center;
      padding: 20px;
      border-radius: 8px;
      background: #f5f7fa;

      .item-icon {
        width: 48px;
        height: 48px;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 16px;

        .el-icon {
          font-size: 24px;
        }
      }

      .item-info {
        .item-value {
          font-size: 24px;
          font-weight: bold;
          line-height: 1;
          margin-bottom: 8px;
        }

        .item-label {
          font-size: 14px;
          color: #909399;
        }
      }

      &.total {
        .item-icon {
          background: #ecf5ff;
          color: #409EFF;
        }
        .item-value {
          color: #409EFF;
        }
      }

      &.month {
        .item-icon {
          background: #f0f9eb;
          color: #67C23A;
        }
        .item-value {
          color: #67C23A;
        }
      }

      &.rank {
        .item-icon {
          background: #fdf6ec;
          color: #E6A23C;
        }
        .item-value {
          color: #E6A23C;
        }
      }
    }
  }

  .chart-card {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      h3 {
        margin: 0;
        font-size: 16px;
        font-weight: 600;
      }
    }

    .chart-container {
      height: 300px;

      .chart-placeholder {
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #f5f7fa;
        color: #909399;
        border-radius: 4px;
      }
    }
  }

  .records-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      h3 {
        margin: 0;
        font-size: 16px;
        font-weight: 600;
      }
    }

    .pagination {
      margin-top: 20px;
      text-align: right;
    }
  }
}
</style> 